package com.lz.library.extension

import java.lang.reflect.ParameterizedType

/**
 *  author: you : 2020/03/31
 */

/**
 * 找出泛型所限定的class
 * @param superClazz 要找的super类
 */
fun <T> Class<*>.findGenericClass(superClazz: Class<*>): Class<T>? {
    var cls: Class<*>? = this
    var findClass: Class<T>? = null
    while (findClass == null && cls != null) {
        val type = cls.genericSuperclass
        if (type is ParameterizedType) {
            for (t in type.actualTypeArguments) {
                when (t) {
                    is Class<*> -> {
                        if (superClazz.isAssignableFrom(t)) {
                            findClass = t as Class<T>
                            break
                        }
                    }
                    is ParameterizedType -> {
                        val rawType = t.rawType
                        if (rawType is Class<*> && superClazz.isAssignableFrom(rawType)) {
                            findClass = rawType as Class<T>
                            break
                        }
                    }
                }
            }
        }
        cls = cls.superclass
    }
    return findClass
}
